package com.example.myapplication.utils;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class ThreadPool {
    private static final int CORE_POOL_SIZE = 5;
    private static final int MAX_POOL_SIZE = 10;
    private static final int KEEP_ALIVE_TIME = 5000;

    private static ThreadPoolExecutor executor;

    static {
        executor = new ThreadPoolExecutor(
                CORE_POOL_SIZE,
                MAX_POOL_SIZE,
                KEEP_ALIVE_TIME,
                TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<Runnable>()
        );
    }
    private static ExecutorService executorService;
    private static ScheduledExecutorService scheduledExecutorService;

    public static void doubleExecute(Runnable runnable) {
        executor.execute(runnable);
    }


    public static void  singleExecute(Runnable runnable){
        executorService = Executors.newSingleThreadExecutor();
        executorService.submit(runnable);
    }
    //android  开启定时任务
    public static void scheduleAtFixedRate(Runnable runnable){
        scheduledExecutorService = Executors.newScheduledThreadPool(1);
        scheduledExecutorService.scheduleAtFixedRate(runnable,0,20,TimeUnit.MINUTES);
    }


    //关闭线程池
    public static void closeExecute(){
        if (executor!=null){
            executor.shutdown();
            executor = null;
        }

        if (executorService!=null){
            executorService.shutdown();
            executorService = null;
        }

        if (scheduledExecutorService!=null){
            scheduledExecutorService.shutdown();
            scheduledExecutorService=null;
        }
    }
}

